#include "mbbms_sd_driver.h"

extern "C" {
void MXD_ISO7816_Init(void);
void MXD_ISO7816_DeInit(void);
void MXD_ISO7816_Reset();
int MXD_ISO7816_Transf(char *pTxData, int txLen, char *pRxData, int rxLen);
void UAMDRV_TRACE(const char *pFormat, ...);
}


#define MAKEWORD(low,high) ((unsigned short)((unsigned char)(low)) | (((unsigned short)(unsigned char)(high))<<8))


int MXD_UAM_Transfers(unsigned char *pBufIn, unsigned int bufInLen, unsigned char *pBufOut, unsigned int *pBufOutLen, unsigned short *sw)
{
	UAMDRV_TRACE("<UAM_Transfers> Enter MXD_UAM_Transfers()\r\n");

    char   cmd[260] = {0}, rsp[256] = {0};
    int    cmdLen = 0, rsplen = 0;
    int ret;

    if (bufInLen == 5)
    {
        /**********************************************************
        APDU CMD FORMAT(Case 2):GET_UAM_CMD
        ***********************************************************/
        memcpy(cmd, pBufIn, 5);

		rsplen = MXD_ISO7816_Transf(cmd, 5, rsp, cmd[4] + 3);

        if (rsplen != (cmd[4] + 3))
        {
            UAMDRV_TRACE("<UAM_Transfers> - Get SW1, SW2 error!!!\r\n");
            return 0;
        }

        *sw = MAKEWORD(rsp[rsplen-1], rsp[rsplen-2]);
        UAMDRV_TRACE("<UAM_Transfers> - *sw = 0x%x\r\n", *sw);

        *pBufOutLen = rsplen - 3;
        memcpy(pBufOut, rsp + 1, *pBufOutLen);
    }
    else if (bufInLen > 5 && bufInLen == (int)pBufIn[4] + 5)
    {
        /**********************************************************
        APDU CMD FORMAT(Case 3):SEND_UAM_CMD
        ***********************************************************/
        memcpy(cmd, pBufIn, bufInLen);

        rsplen = MXD_ISO7816_Transf(cmd, 5, rsp, 1);

        if (rsplen != 1)
        {
            UAMDRV_TRACE("<UAM_Transfers> - send/recv cmd fail!!!\r\n");
            return 0;
        }

		rsplen = MXD_ISO7816_Transf(&cmd[5], cmd[4], rsp, 2);

        if (rsplen != 2)
        {
            UAMDRV_TRACE("<UAM_Transfers> - Get SW1, SW2 error!!!\r\n");
            return 0;
        }

        *sw = MAKEWORD(rsp[rsplen - 1], rsp[rsplen - 2]);

        UAMDRV_TRACE("<UAM_Transfers> - sw = 0x%x\r\n", *sw);

        *pBufOutLen = 0;
    }
    else if (bufInLen > 5 && bufInLen > (int)pBufIn[4] + 5)
    {
		UAMDRV_TRACE("<UAM_Transfers> - Error param\r\n");
        return 0;
    }

    return 1;
}

int MXD_UAM_Init(void)
{
	UAMDRV_TRACE("<UAM_DRV> Enter MXD_UAM_Init()\r\n");
	MXD_ISO7816_Init();

	return 1;
}

int MXD_UAM_DeInit(void)
{
	UAMDRV_TRACE("<UAM_DRV> Enter MXD_UAM_DeInit()\r\n");
	MXD_ISO7816_DeInit();

	return 1;
}

int MXD_UAM_Reset(void)
{
	UAMDRV_TRACE("<UAM_DRV> Enter MXD_UAM_Reset()\r\n");
	MXD_ISO7816_Reset();

	return 1;
}
